import { ref, shallowRef } from 'vue'

import { getQuizResult } from '../../api'
import { imagePath } from '@/libs/file-utils'
import { catchFn } from '@/libs/common'
import { loading } from '@/libs/message'
import { userInfo } from '@/libs/user'

/** 每日一算结果 */
const result = shallowRef<T_FortuneResult>()
/** 结果ID */
let resultId = 0
/** MBTI类型 */
const mbtiType = ref('')
/** 是否未解锁高级报告 */
const lockedStatus = shallowRef<{
  /** 提示文字 */
  itemId: number
  /** 提示文字 */
  tip: string
  /** 解锁价格 */
  price: number
}>()
const defaultScore = ref(80)

/** 类型列表 */
const typeList = [
  {
    key: 1,
    name: '日运',
  },
  {
    key: 2,
    name: '月运',
  },
  {
    key: 3,
    name: '年运',
  },
]
/** 当前类型, 1日2月3年 */
const curType = ref(1)

/** 日期列表 */
const dateList = shallowRef<{
  [key: string]: string[]
}>({
  1: ['01', '02', '03', '04', '05', '06', '07'],
  2: ['01', '02', '03', '04', '05', '06', '07'],
  3: ['2023', '2024', '2025', '2026', '2027'],
})
/** 当前选择年份 */
const curYearIdx = ref(2)
/** 当前选择月份 */
const curMonthIdx = ref(3)
/** 当前选择日期 */
const curDayIdx = ref(3)

const defaultFortuneList = [
  {
    icon: imagePath('quiz/fortune/result/icon-love.png'),
    key: 'love',
    score: 50,
    title: '',
    shortTitle: '',
    color_bg: 'rgba(219, 97, 172, .64)',
    color_inner_in: 'rgba(179, 34, 155, 0.52)',
    color_inner_out: '#6F0664',
    desc: '',
  },
  {
    icon: imagePath('quiz/fortune/result/icon-wealth.png'),
    key: 'wealth',
    score: 50,
    title: '',
    shortTitle: '',
    color_bg: 'rgba(245, 149, 5, .64)',
    color_inner_in: 'rgba(179, 85, 34, 0.52)',
    color_inner_out: '#6F3E06',
    desc: '',
  },
  {
    icon: imagePath('quiz/fortune/result/icon-career.png'),
    key: 'career',
    score: 50,
    title: '',
    shortTitle: '',
    color_bg: 'rgba(149, 64, 209, .64)',
    color_inner_in: 'rgba(119, 34, 179, 0.52)',
    color_inner_out: '#4B066F',
    desc: '',
  },
  {
    icon: imagePath('quiz/fortune/result/icon-health.png'),
    key: 'health',
    score: 50,
    title: '',
    shortTitle: '',
    color_bg: 'rgba(58, 147, 0, .64)',
    color_inner_in: 'rgba(35, 149, 31, 0.52)',
    color_inner_out: '#066F19',
    desc: '',
  },
]
const fortuneList = shallowRef<
  {
    icon: string
    key: T_FortuneType
    score: number
    title: string
    shortTitle: string
    color_bg: string
    color_inner_in: string
    color_inner_out: string
    desc: string
  }[]
>(JSON.parse(JSON.stringify(defaultFortuneList)))

const suggestionTitle: { [key: string]: string } = {
  1: imagePath('quiz/fortune/result/suggestion-day.png'),
  2: imagePath('quiz/fortune/result/suggestion-month.png'),
  3: imagePath('quiz/fortune/result/suggestion-year.png'),
}

const typeTitle: { [key: string]: string } = {
  1: '今日',
  2: '本月',
  3: '本年',
}

const suggestionIcons: { [key: string]: string } = {
  money_icon: imagePath('quiz/fortune/result/suggestion-icon-money.png '),
  star_icon: imagePath('quiz/fortune/result/suggestion-icon-star.png '),
  cloth_icon: imagePath('quiz/fortune/result/suggestion-icon-cloth.png '),
  car_icon: imagePath('quiz/fortune/result/suggestion-icon-car.png '),
  love_icon: imagePath('quiz/fortune/result/suggestion-icon-love.png '),
  work_icon: imagePath('quiz/fortune/result/suggestion-icon-work.png '),
}

const suggestionList = shallowRef<
  {
    title: string
    icon: string
    description: string
  }[]
>([])

export {
  result,
  resultId,
  mbtiType,
  defaultScore,
  lockedStatus,
  typeList,
  curType,
  dateList,
  curYearIdx,
  curMonthIdx,
  curDayIdx,
  fortuneList,
  suggestionTitle,
  typeTitle,
  suggestionList,
}

/**
 * 初始化
 */
const init = () => {
  const date = new Date()
  const time = date.getTime()
  const dayTime = 24 * 60 * 60 * 1000
  const curMonth = date.getMonth() + 1
  const curYear = date.getFullYear()

  defaultScore.value = Math.round(Math.random() * 40 + 60)
  dateList.value = {
    1: [-3, -2, -1, 0, 1, 2, 3].map(val => {
      date.setTime(time + val * dayTime)

      return date.getDate().toString().padStart(2, '0')
    }),
    2: [-3, -2, -1, 0, 1, 2, 3].map(val => {
      let i = curMonth + val

      if (i < 1) i += 12
      else if (i > 12) i -= 12

      return i.toString().padStart(2, '0')
    }),
    3: [-2, -1, 0, 1, 2].map(val => (curYear + val).toString()),
  }

  updateResult()
}

/**
 * 更新测试结果
 */
const updateResult = (showLoading = true) =>
  catchFn(
    async () => {
      showLoading && loading(true)

      const { data } = await getQuizResult({
        typeCode: 'fortune',
        type: curType.value,
        date: `${dateList.value[3][curYearIdx.value]}-${
          curType.value > 2 ? '01' : dateList.value[2][curMonthIdx.value]
        }-${curType.value > 1 ? '01' : dateList.value[1][curDayIdx.value]}`,
      })

      userInfo.value = data.userInfo
      result.value = data.fortuneResult
      resultId = data.id
      mbtiType.value = data.userInfo.mbtiType
      lockedStatus.value = data.isLocked
        ? {
            itemId: data.unlockItemId,
            tip: data.unlockText,
            price: data.unlockItemPrice || 48,
          }
        : undefined

      // 未加载完成
      if (data.testStatus === 1 || !result.value) {
        startPollingQuery()
        return
      } else loading(false)

      fortuneList.value = fortuneList.value.map(item => {
        const tar = result.value?.[item.key]

        if (tar) {
          item.score = tar.score
          item.title = tar.title
          item.shortTitle = tar.shortTitle
          item.desc = tar.description
        }

        return item
      })

      if (result.value.suggestions) {
        suggestionList.value = result.value.suggestions.map(item => {
          item.icon = suggestionIcons[item.icon]

          return item
        })
      } else {
        suggestionList.value = []

        startPollingQuery(false)
      }
    },
    { disableLoading: true },
  )

/** 轮询函数 */
let queryFn: any = null

/**
 * 开始轮询查询
 */
const startPollingQuery = (showLoading = true) => {
  queryFn = setTimeout(() => {
    queryFn = null
    updateResult(showLoading)
  }, 2000)
}

/**
 * 结束轮询查询
 */
const stopPollingQuery = () => {
  queryFn && clearTimeout(queryFn)
  queryFn = null
}

/**
 * 切换类型
 * @param key 类型
 */
const switchType = (key: number) => {
  if (curType.value === key) return

  curType.value = key

  stopPollingQuery()
  updateResult()
}

/**
 * 切换日期
 * @param idx 序号
 */
const switchDate = (idx: number) => {
  if (curType.value === 1) {
    if (curDayIdx.value === idx) return
    else curDayIdx.value = idx
  } else if (curType.value === 2) {
    if (curMonthIdx.value === idx) return
    else curMonthIdx.value = idx
  } else if (curType.value === 3) {
    if (curYearIdx.value === idx) return
    else curYearIdx.value = idx
  } else return

  stopPollingQuery()
  updateResult()
}

/**
 * 还原状态
 */
const clear = () => {
  curType.value = 1
  curYearIdx.value = 2
  curMonthIdx.value = 3
  curDayIdx.value = 3

  result.value = undefined
  fortuneList.value = JSON.parse(JSON.stringify(defaultFortuneList))

  stopPollingQuery()
  loading(false)
}

export { init, updateResult, switchType, switchDate, clear }
